package org.cloud.jiangyouuser.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.cloud.jiangyoucommon.common.Result;
import org.cloud.jiangyouuser.dto.LoginDTO;
import org.cloud.jiangyouuser.entity.pojo.User;
import org.cloud.jiangyouuser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户信息 Controller层
 * @Author: liupy
 * @Date: 2024/1/1
 */
@Slf4j
@RestController
@RequestMapping("/users")
@Api(value = "用户相关接口", tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public Result login(@Valid @RequestBody LoginDTO loginDTO, BindingResult bindingResult) {
        log.info("用户登录接口入参：loginDTO={}", loginDTO);
        try {
            if (bindingResult.hasErrors()) {
                return Result.fail(bindingResult.getFieldError().getDefaultMessage());
            }
            return userService.login(loginDTO);
        } catch (Exception e) {
            log.error("用户登录接口异常：{}", e.getMessage(), e);
            return Result.fail("用户登录接口异常");
        }
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        log.info("用户注册接口入参：user={}", user);
        try {
            return userService.register(user);
        } catch (Exception e) {
            log.error("用户注册接口异常：{}", e.getMessage(), e);
            return Result.fail("用户注册接口异常");
        }
    }

    @ApiOperation(value = "获取所有用户信息")
    @GetMapping("/list")
    public Result getAllUsers() {
        try {
            return userService.getAllUsers();
        } catch (Exception e) {
            log.error("获取所有用户信息接口异常：{}", e.getMessage(), e);
            return Result.fail("获取所有用户信息异常");
        }
    }

    @ApiOperation(value = "根据id查询用户信息")
    @GetMapping("/{id}")
    public Result queryById(@ApiParam(value = "用户id") @PathVariable("id") String id) {
        log.info("根据id查询用户信息接口入参：userId={}", id);
        try {
            return userService.queryById(id);
        } catch (Exception e) {
            log.error("根据id查询用户信息接口异常：{}", e.getMessage(), e);
            return Result.fail("根据id查询用户信息异常");
        }
    }

    @ApiOperation(value = "根据账号查询用户信息")
    @GetMapping("/userInfo")
    public Result queryByUserName(@ApiParam(value = "账号") @RequestParam("account") String account) {
        log.info("根据账号查询用户信息接口入参：account={}", account);
        try {
            return userService.queryByUserName(account);
        } catch (Exception e) {
            log.error("根据账号查询用户信息接口异常：{}", e.getMessage(), e);
            return Result.fail("根据账号查询用户信息异常");
        }
    }
}
